<?php

namespace Iwesen\Sem\Track\Advertisers;

class Oceanengine
{
    protected $api =  "https://analytics.oceanengine.com/api/v2/conversion";

    public function callback($param)
    {
        $clickId = isset($param['clickid']) ? $param['clickid'] : null;

        if (!$clickId) {
            throw new \Exception('clickid is required!');
        }
        if (!isset($param['event_type']) || !$event_type = $param['event_type']) {
            $event_type = config('sem-track.oceanengine.event_type');
            if (!$event_type) {
                throw new \Exception('event_type is not a exist !');
            }
        }
        try {
            $time = time();
            $params = [
                "event_type" => $event_type,
                "context" => [
                    "ad" => [
                        "callback" => $clickId,
                    ],
                ],
                "timestamp" => $time,
            ];
            $result = (new Request())->_request($this->api, [
                'Content-Type' => 'application/json',
            ], $params);
            $data = json_decode($result, true);
            if ($data['code'] == 0) {
                return 'success';
            }
            return 'fail';
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
}
